package com.veetao.api.config;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfig {

	
	@Value("${redis.pool.max-idle}")
	private int maxIdle;
	
	@Value("${redis.pool.min-idle}")
	private int minIdle;
	
	@Value("${redis.pool.max-active}")
	private int maxActive;

	@Value("${redis.pool.max-wait}")
	private long maxWait;
	
	@Value("${redis.timeout}")
	private int timeout;
	
	
	private List<HostAndPort> redisHostList;
	
	@Value("${redis.server}")
	public void setRedisHosts(String redisHosts) {
		redisHostList = new ArrayList<HostAndPort>();
		if(StringUtils.isEmpty(redisHosts)) {
			throw new IllegalArgumentException("redis host expected");
		}
		
		String[] hostAndPortList = redisHosts.split(",");
		for(String hostAndPort : hostAndPortList) {
			String[] arr = hostAndPort.split(":");
			if(arr.length !=2 ) {
				throw new IllegalArgumentException("illegal redis host: " + hostAndPort);
			}
			
			redisHostList.add(new HostAndPort(arr[0], Integer.parseInt(arr[1])));
			
		}
	}
	
	
	
/*	@Value("${expression.redis.pool.database}")
	private int database;*/
	
	@Bean
	public JedisPoolConfig jedisPoolConfig() {
		JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
		jedisPoolConfig.setMaxIdle(maxIdle);
		jedisPoolConfig.setMinIdle(minIdle);
		jedisPoolConfig.setMaxWaitMillis(maxWait);
		jedisPoolConfig.setMaxTotal(maxActive);
		jedisPoolConfig.setTestOnBorrow(false);
		return jedisPoolConfig;
	}
	
	@Bean
	public JedisCluster jedisClusterTemplate(){
		Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>();
		jedisClusterNodes.addAll(redisHostList);
//		JedisCluster jc = jedisPoolConfig()
		return null;
	}
	
	@Bean
	public JedisPool jedisPool(){
		HostAndPort hp = this.redisHostList.get(0);
		JedisPool pool = new JedisPool(jedisPoolConfig(),hp.getHost(),hp.getPort());
		return pool;
	}
	

}
